package com.example.system.interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.common.core.Result;
import com.example.common.core.ResultGenerator;
import com.example.system.annotation.HasPermission;
import com.example.system.dao.ResourceDao;
import com.example.system.dto.ResourceResult;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Resource
    private ResourceDao resourceDao;
    @Resource
    private ValueOperations valueOperations;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            Result result = ResultGenerator.genFailResult("token不能为空");
            writer.write(JSONUtil.toJsonStr(result));
            writer.close();
            return false;
        }
        String TOKEN_KEY = "system:token:";
        String id = (String) valueOperations.get(TOKEN_KEY + token);
        if (StrUtil.isEmpty(id)) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            Result result = ResultGenerator.genFailResult("token已失效");
            writer.write(JSONUtil.toJsonStr(result));
            writer.close();
            return false;
        }
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            HasPermission hasPermission = handlerMethod.getMethod().getAnnotation(HasPermission.class);
            if (ObjectUtil.isNotNull(hasPermission) && StrUtil.isNotBlank(hasPermission.value())) {
                List<ResourceResult> resourceResults = CollUtil.newArrayList();
                resourceResults = resourceDao.selectResourcesByAdminId(Integer.valueOf(id));
                boolean flag = Stream.of(StringUtils.join(resourceResults.stream().filter(resourceResult -> resourceResult.getStatus() == 1 && resourceResult.getType() == 2).map(ResourceResult::getTag).collect(Collectors.toList()), ',').split(",")).collect(Collectors.toList()).contains(hasPermission.value());
                if (!flag) {
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/json; charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    Result result = ResultGenerator.genFailResult("权限不足");
                    writer.write(JSONUtil.toJsonStr(result));
                    writer.close();
                    return false;
                }
            }
        }
        return true;
    }
}
